package com.ssm.basis.web.config.security;

import org.springframework.boot.autoconfigure.session.DefaultCookieSerializerCustomizer;
import org.springframework.boot.autoconfigure.session.SessionAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration;
import org.springframework.session.web.http.DefaultCookieSerializer;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

import static com.ssm.basis.service.constant.SecurityConstant.HEADER_X_AUTH_TOKEN;

/**
 * @see EnableRedisHttpSession
 * @see SessionAutoConfiguration
 * @see RedisHttpSessionConfiguration
 * https://docs.spring.io/spring-session/reference/spring-security.html
 */
@Configuration(proxyBeanMethods = false)
class SessionConfig {
    /**
     * 使用 http head 传递 token id
     * https://docs.spring.io/spring-session/reference/http-session.html#rest-spring-configuration
     */
    @Bean
    // @ConditionalOnExpression("${server.servlet.session.cookie.http-only:false} == false")
    HttpSessionIdResolver httpSessionIdResolver() {
        // return HeaderHttpSessionIdResolver.xAuthToken();
        return new HeaderHttpSessionIdResolver(HEADER_X_AUTH_TOKEN);
    }

    /**
     * @see DefaultCookieSerializer
     */
    // @Bean
    // 配置中查找 server.servlet.session.cookie.http-only 的值，能找到且值为 false 就注入，没找到也注入(matchIfMissing = true)
    // @ConditionalOnProperty(prefix = "server.servlet.session.cookie", name = "http-only", havingValue = "true", matchIfMissing = true)
    DefaultCookieSerializerCustomizer cookieSerializerCustomizer() {
        return cookieSerializer -> {
            cookieSerializer.setCookieName("JSESSIONID");
            cookieSerializer.setCookiePath("/");
            cookieSerializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
        };
    }
}
